#include "LuaHandler.h"
#include <iostream>

#include "ObjectManager.h"

extern ObjectManager* om;	// ATTENTION VIRER CA QUAND PROB ACCES A L'OM SERA REGLE

int LUA_C_PrintMe(lua_State *L)
{
    int argc = lua_gettop(L);

    std::cerr << "-- my_function() called with " << argc
        << " arguments:" << std::endl;

    for ( int n=1; n<=argc; ++n ) {
        std::cout << lua_tostring(L, n) << std::endl;
    }

    //lua_pushnumber(L, 123); // return value
    return 0; // number of return values
}

int LUA_C_TurnLeft(lua_State* L)
{
	om->RotateItem(1, 10.0);

	return 0;
}

LuaHandler::LuaHandler(std::string codeFile, ObjectManager* _om)
{
	om = _om;
    Loaded=false;

    L = lua_open();

    luaopen_base(L);
    luaopen_table(L);
    luaopen_string(L);
    luaopen_math(L);
    
    lua_register(L,"PrintMe", LUA_C_PrintMe);
	lua_register(L,"TurnLeft",  LUA_C_TurnLeft);
	//lua_register(L,"Process", C_LUA_Process);
	//lua_register(L,"Process", LuaProcess);

    Loaded = luaL_loadfile(L, codeFile.c_str()) == 0;
}

LuaHandler::~LuaHandler()
{

}

void LuaHandler::Run()
{
    if(!Loaded)
        return;
    lua_pcall(L, 0, LUA_MULTRET, 0);
}

void LuaHandler::CallLuaFunction(const char* functionName)
{
	/* the function name */
	lua_getglobal(L, functionName);

	/* call the function with 2
	arguments, return 1 result */
	lua_call(L, 0, 0);


// 	lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
// 	lua_pushstring(L, "how");                        /* 1st argument */
// 	lua_getfield(L, LUA_GLOBALSINDEX, "t");   /* table to be indexed */
// 	lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
// 	lua_remove(L, -2);                  /* remove 't' from the stack */
// 	lua_pushinteger(L, 14);                          /* 3rd argument */
// 	lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
// 	lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global 'a' */

}

